package com.jessehu.xutilstest;

import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.jessehu.xutilstest.utils.MyToast;

import org.xutils.common.Callback;
import org.xutils.common.task.PriorityExecutor;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;

public class DownloadTestActivity extends AppCompatActivity {

    private DownloadTestActivity TAG;
    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download_test);
        TAG = this;
        downloadApk();
    }
    //下载apk
    private void downloadApk(){
        String downloadUrl = "http://192.168.218.131:8080/1.apk";
        RequestParams params = new RequestParams(downloadUrl);
        params.setAutoResume(true);//设置是否在下载是自动断点续传
        params.setAutoRename(false);//设置是否根据头信息自动命名文件
        params.setSaveFilePath(getExternalCacheDir().getAbsolutePath()+"/1.apk");//下载路径
        params.setExecutor(new PriorityExecutor(3,true));//自定义线程池,
        params.setCancelFast(true);//是否可以被立即停止.
        x.http().get(params, new Callback.ProgressCallback<File>() {
            @Override
            public void onSuccess(File result) {
                MyToast.showToast(TAG,"下载成功");
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyToast.showToast(TAG,"下载出错");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mProgressDialog.dismiss();
            }

            @Override
            public void onWaiting() {

            }

            @Override
            public void onStarted() {
                downloadDialog();
            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                if (isDownloading){
                    mProgressDialog.setMax((int) total);
                    mProgressDialog.setProgress((int) current);
                }
            }
        });
    }

    //创建进度条弹窗
    private void downloadDialog(){
        mProgressDialog = new ProgressDialog(TAG);
        mProgressDialog.setTitle("downloading");
        mProgressDialog.setCancelable(true);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCanceledOnTouchOutside(true);
        mProgressDialog.show();
    }

}
